#include<vector>
#include<string>
using namespace std;
class Solution {
private:
    int findParent(int x, vector<int>& p) {
        return x == p[x] ? x : (p[x] = findParent(p[x], p));
    }

    void merge(int x,int y,vector<int>&p) {
        int px = findParent(x, p);
        int py = findParent(y, p);
        if (px != py) {
            p[px] = py;
        }
    }

public:
    int regionsBySlashes(vector<string>& grid) {
        int rows = grid.size();
        int cols = grid[0].size();
        vector<int> parents(rows * cols * 4);
        for (int i = 0; i < parents.size(); ++i)
            parents[i] = i;
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (grid[i][j] == '/'|| grid[i][j]==' ') {
                    merge(i * 4 * cols + 4 * j + 0, i * 4 * cols + 4 * j + 1, parents);
                    merge(i * 4 * cols + 4 * j + 2, i * 4 * cols + 4 * j + 3, parents);
                }
                if (grid[i][j] == '\\' || grid[i][j] == ' ') {
                    merge(i * 4 * cols + 4 * j + 1, i * 4 * cols + 4 * j + 2, parents);
                    merge(i * 4 * cols + 4 * j + 0, i * 4 * cols + 4 * j + 3, parents);
                }
                if (j != cols - 1) {
                    merge(i * 4 * cols + 4 * j + 2, i * 4 * cols + 4 * (j + 1) + 0, parents);
                }
                if (i != rows - 1) {
                    merge(i * 4 * cols + 4 * j + 3, (i + 1) * 4 * cols + 4 * j + 1, parents);
                }
            }
        }
        int res = 0;
        for (int i = 0; i < parents.size(); ++i) {
            if (findParent(i, parents) == i)++res;
        }
        return res;
    }
};